package tw.com.lacammy.mcoupon;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;


public class ARCompass extends Activity implements SurfaceHolder.Callback {
	
	 private WebView mWebView;
	 private SensorManager mSensorManager;
	 private float[] mValues;
	 private boolean compassOn = false;

	 private static final String TAG = "ARCompass";
	 final Context mContext = this;

	 private Camera mCamera;
	 private SurfaceView mSurfaceView;
	 private SurfaceHolder mSurfaceHolder;
	 private boolean mPreviewRunning;
	 private final SensorEventListener mListener =
		   new SensorEventListener() {
		  @Override
		  public void onAccuracyChanged
		   (Sensor sensor, int accuracy) {
		  }
		  @Override
		  public void onSensorChanged(SensorEvent event) {
		   mValues = event.values;
		   Log.d(TAG,"Compass update: " + mValues[0]);
		   String url =
		    "javascript:updateView(" + mValues[0] + ");";
		   mWebView.loadUrl(url);
		  }
		 };

		 
		 /** Called when the activity is first created. */
		 @Override
		 public void onCreate(Bundle savedInstanceState) {
		  super.onCreate(savedInstanceState);
		  Log.d(TAG, "onCreate");
		  // Get rid of title
		  requestWindowFeature(Window.FEATURE_NO_TITLE);

		  setContentView(R.layout.main);

		  // Initialize the surface for camera preview
		  mSurfaceView =
		   (SurfaceView)findViewById(R.id.preview);
		  mSurfaceHolder = mSurfaceView.getHolder();
		  mSurfaceHolder.addCallback(this);
		  mSurfaceHolder.setType
		   (SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		  Log.d(TAG, "SurfaceView initialized");

		  // Initialize the WebView
		  mWebView = (WebView) findViewById(R.id.webView0);
		  WebSettings webSettings = mWebView.getSettings();
		  webSettings.setSavePassword(false);
		  webSettings.setSaveFormData(false);
		  webSettings.setJavaScriptEnabled(true);
		  webSettings.setSupportZoom(false);
		  mWebView.setBackgroundColor(0);

		  mWebView.addJavascriptInterface
		   (new CompassJavaScriptInterface(), "direction");
		  Log.d(TAG, "JavaScript interface added");

		  /* Set WebChromeClient before calling loadUrl! */
		  mWebView.setWebChromeClient
		   (new WebChromeClient() {
		   @Override
		   public boolean onJsAlert(
		    WebView view, String url, String message,
		    final android.webkit.JsResult result){
		    new AlertDialog.Builder(mContext)
		    .setTitle("javaScript dialog")
		    .setMessage(message)
		    .setPositiveButton(android.R.string.ok,
		    new AlertDialog.OnClickListener() {
		     public void onClick(
		      DialogInterface dialog, int which) {
		      result.confirm();
		     }
		    })
		    .setCancelable(false)
		    .create()
		    .show();
		    return true;
		   };
		  });

		  mWebView.loadUrl(
		   "file:///android_asset/www/arcompass.html");
		 }

		 
		 final class CompassJavaScriptInterface {
			  /* Note this runs in a separate thread */

			  CompassJavaScriptInterface() {
			  }
			  public void turnOnCompass() {
			   Log.d(TAG, "turnOnCompass");
			   mSensorManager = (SensorManager)
			     getSystemService(Context.SENSOR_SERVICE);
			   Sensor mSensor =
			     mSensorManager.getDefaultSensor
			       (Sensor.TYPE_ORIENTATION);

			   if(mSensor != null){
			    mSensorManager.registerListener(mListener,
			     mSensor, SensorManager.SENSOR_DELAY_NORMAL);
			    compassOn = true;
			    Log.d(TAG, "Compass started");
			   }
			   else{
			    Toast.makeText(mContext,
			      "No ORIENTATION Sensor",
			      Toast.LENGTH_LONG).show();
			    compassOn = false;
			    finish();
			   }

			  }
			 }

			 @Override
			 protected void onDestroy() {
			 super.onDestroy();
			  if(compassOn){
			  mSensorManager.unregisterListener(mListener);
			  }
			 finish();
			 }
			// Create camera preview.
			 public void surfaceCreated(SurfaceHolder holder){
			  mCamera = Camera.open();
			  try {
			   mCamera.setPreviewDisplay(holder);
			  } catch (IOException exception) {
			   mCamera.release();
			   mCamera = null;
			  }
			 }

			 // Change preview's properties
			 public void surfaceChanged(SurfaceHolder holder,
			   int format, int w, int h){
			  mCamera.startPreview();
			  mPreviewRunning = true;
			 }

			 // Stop the preview.
			 public void surfaceDestroyed
			   (SurfaceHolder holder){
			  mCamera.stopPreview();
			  mPreviewRunning = false;
			  mCamera.release();
			 }
			}

